package crawler.client.core.handle;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import crawler.utility.date.TimeUtility;
import crawler.utility.file.FileOperation;

@Service
public class ClientGroupHandle {

	private static Logger log = LoggerFactory.getLogger(ClientGroupHandle.class);

	@Autowired
	private PathHandle pathHandle;

	public String fetchClientGroup() {
		String currentClientGroup = "";

//		long currentTime = TimeUtility.getCurrentLongTime();
//		
//		JSONObject fileJSON = new JSONObject();
//		fileJSON.put("clientGroup", clientGroup);
//		fileJSON.put("currentTime", currentTime);
//
//		String filein = fileJSON.toJSONString() + FileOperation.LINE_SEPARATOR;// 新写入的行+换行

		try {

			String pathName = pathHandle.getBasePath() + "/clientGroup.properties";
			FileOperation fileOperation = new FileOperation(pathName);

			if (fileOperation.exists()) {

				currentClientGroup = fileOperation.readContentFile();

				log.info("Get Exists clientGroup : " + currentClientGroup);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			log.info("fetchClientGroup Error : ", e);
		} catch (IOException e) {
			e.printStackTrace();
			log.info("fetchClientGroup Error : ", e);
		}

		return currentClientGroup;
	}

	public void updateClientGroup(String clientGroup) {
		String currentClientGroup = "";

		long currentTime = TimeUtility.getCurrentLongTime();

		JSONObject fileJSON = new JSONObject();
		fileJSON.put("clientGroup", clientGroup);
		fileJSON.put("currentTime", currentTime);

		String filein = fileJSON.toJSONString() + FileOperation.LINE_SEPARATOR;// 新写入的行+换行

		try {

			String pathName = pathHandle.getBasePath() + "/clientGroup.properties";
			FileOperation fileOperation = new FileOperation(pathName);

			if (!fileOperation.exists()) {

				fileOperation.createContentFile(filein);

				log.info("Create clientGroup : " + clientGroup);
			} else {

				fileOperation.writeContentFile(filein);

				log.info("Update Exists clientGroup : " + currentClientGroup);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			log.info("updateClientGroup Error : ", e);
		} catch (IOException e) {
			e.printStackTrace();
			log.info("updateClientGroup Error : ", e);
		}

	}
}
